package com.think.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Objects;

public class ExceptionFilter implements Filter {

    public void init(FilterConfig config) {

    }

    //todo 待优化 ，排除资源文件
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 是否已经放有异常栈, 避免循环
        boolean isRethrow = !Objects.isNull(request.getAttribute("exp"));
        if (isRethrow) {
            filterChain.doFilter(request, response);
            return;
        }
        try {
            filterChain.doFilter(request, response);
        } catch (RuntimeException e) {
            // 发生异常，保存异常栈
            request.setAttribute("exp", e);
            request.getRequestDispatcher("/error/rethrow").forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
